package cn.vic.genertor.engine;

import cn.org.rapid_framework.generator.GeneratorFacade;
import cn.org.rapid_framework.generator.util.SystemHelper;
import cn.vic.db.model.Table;
import cn.vic.model.RepidModel;
import org.apache.log4j.Logger;

import java.io.File;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by vic on 2017/8/11.
 *
 * @author vic
 */
public class FreeMarkrTemplate implements GenerateInterface {

    private static final Logger LOGGER = Logger.getLogger(FreeMarkrTemplate.class);

    private static final String DEFAULT_ENCODING = "UTF-8";

    private boolean hasOpen = false;

    @Override
    public void setHasOpen(boolean hasOpen) {
        this.hasOpen = hasOpen;
    }

    /**
     * 1.使用Set 给字段中类型去重，作为引包
     * 2.包名
     * 3.工具类
     */
    @Override
    public void processToFile(RepidModel model) {
        try {
            GeneratorFacade facade = new GeneratorFacade(); //这里有设置输出路径
            facade.setOutRootDir(model.getSavePath());
            facade.getGenerator().setIncludes(null);//匹配模版
            facade.getGenerator().addTemplateRootDir(new File(model.getTemplatePath()));//模版路径
            for (Table tableModel : model.getTableModels()) {
                Map param = new HashMap();
                // reqid table 支持框架多,功能强大，这个可配置性强
                param.put("className", tableModel.getClassName());
                param.put("sqlName", tableModel.getTableName());
                param.put("basePackage", model.getPackages());
                param.put("module", model.getModule());
                if (model.getCustomParam() != null) {
                    param.putAll(model.getCustomParam());
                }
                facade.generateByTable(tableModel, param, model.isCover());
            }
            if (SystemHelper.isWindowsOS && hasOpen) {
                Runtime.getRuntime().exec("cmd.exe /c start " + model.getSavePath().replace('/', '\\'));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
